package com.example.javaee.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javaee.common.result;
import com.example.javaee.entity.Asset;
import com.example.javaee.entity.User;
import com.example.javaee.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public result<User> login(HttpServletRequest request, @RequestBody User user) {
        //1、将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User us = userService.getOne(queryWrapper);
        //3、如果没有查询到则返回登录失败结果
        if (us == null) {
            return result.error("账号不存在");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if (!us.getPassword().equals(password)) {
            return result.error("登陆失败");
        }
        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("user", us.getId());
        return result.success(us, "登陆成功");
    }
    @PostMapping("/logout")
    public result<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("user");
        return result.success(null,"退出成功");
    }

    @PostMapping("/register")
    public  result<String> register(HttpServletRequest request,@RequestBody User user){
        //获取属性，密码需要进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);
        //根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (userService.getOne(queryWrapper)!=null){
            return result.error("账号已存在");
        }
        userService.save(user);
        return result.success(null,"注册成功");

    }

    @GetMapping("/{username}")
    public result<User> labelPage( @PathVariable String username) {
        // 条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 如果有输入条件，则加入对name字段的筛选条件
        queryWrapper.eq(User::getUsername, username);
        // 分页查询
        User us = userService.getOne(queryWrapper);
        return result.success(us, "查询成功");
    }

}